﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace DXApplication2
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        string conn = @"Data Source=VANHUNG;database=lichthi;Integrated Security=true";
        DataTable kq = new System.Data.DataTable();
        DataTable vephai = new System.Data.DataTable();
        DataTable lichbanphong = new DataTable();
        DataTable monhoc = new DataTable();
        DataTable vetrai = new DataTable();
        int z=0;
        List<clsNgay> dsngay;
        SqlConnection con;
        public Form1()
        {
            InitializeComponent();
            kq.Columns.Add("malop");            
            kq.Columns.Add("maphong");
            kq.Columns.Add("ngay");
            kq.Columns.Add("siso");
            kq.Columns.Add("succhua");
            kq.Columns.Add("cathi");
            kq.Columns.Add("thoiluongthi");
            con = new SqlConnection(conn);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dsngay = new List<clsNgay>();
            DateTime a = dateTimePicker1.Value;
            vephai = taovephai();
            lichbanphong = laylichbanphong();
            while (a <= dateTimePicker2.Value)
            {
                for (int i = 0; i < vephai.Rows.Count; i++)
                {
                    clsNgay day = new clsNgay(a, vephai.Rows[i]["maphong"].ToString(), int.Parse(vephai.Rows[i]["succhua"].ToString()), int.Parse(vephai.Rows[i]["loaiphong"].ToString()));
                    dsngay.Add(day);                    
                }
                a = a.AddDays(1);
            }
            try
            {
                con.Open();               
                vetrai=taovetrai();
                
                monhoc = getmonhoc();
                DataView dv = new DataView(vetrai);
                for (int i = 0; i < monhoc.Rows.Count; i++)
                {
                    dv.RowFilter = "mamonhoc='" + monhoc.Rows[i]["mamon"] + "'";
                    string[] s = new string[3];
                    int count = 0;
                    for (int j = 0; j < dv.Count; j++)
                    {
                        count++;                        
                        if (count == 1)
                        {
                            s = timngayphuhop(dv[j].Row, int.Parse(dv[j].Row["siso"].ToString()));
                            if (s == null)
                            {                                
                                int[] t = chialopthi(dv[j].Row);
                                List<clsNgay> listphong = ktsoluongphong(t[1],int.Parse(dv[j].Row["thoiluongthi"].ToString()));
                                for (int h = 1; h <= t[0]; h++)
                                {                                  
                                    if(h==1)
                                    {
                                        s = lopghepphong(dv[j].Row, t[1]);
                                        if (s != null)
                                            break;
                                    }                                        
                                    else
                                    {
                                        if (h < t[0])
                                        {
                                            if(!ghepngay(s,  dv[j].Row, t[1]))
                                                MessageBox.Show("hue");
                                        }
                                        else
                                        {
                                            int siso1 = int.Parse(dv[j].Row["siso"].ToString()) - (t[1] * (t[0] - 1));
                                            if(!ghepngay(s, dv[j].Row, siso1))
                                                MessageBox.Show("hung");                                                
                                        }
                                    }
                                    
                                }
                            }
                        }
                        else
                        {
                            if (!ghepngay(s, dv[j].Row, int.Parse(dv[j].Row["siso"].ToString())))
                            {                                
                                int[] t = chialopthi(dv[j].Row);
                                string[] s1 = new string[3];
                                List<clsNgay> listphong = ktsoluongphong(t[1], int.Parse(dv[j].Row["thoiluongthi"].ToString()));
                                for (int h = 1; h <= t[0]; h++)
                                {        
                                    if (h < t[0])
                                    {
                                        ghepngay(s, dv[j].Row, t[1]);

                                    }
                                    else
                                    {
                                        int siso1 = int.Parse(dv[j].Row["siso"].ToString()) - (t[1] * (t[0] - 1));
                                        ghepngay(s,  dv[j].Row, siso1);
                                    }
                                }
                            }
                        }
                    }
                }
                dataGridView1.DataSource =kq;                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
            finally
            {
                con.Close();
            }
        }
        string[] lopghepphong(DataRow lop, int siso)
        {
            DataRow dr0 = kq.NewRow();
            string[] s = new string[3];
            int min = 1000,h=0,succhua=0;
            string maphong = "", ngay = "",cathi="";
            for (int i = 0; i < dsngay.Count; i++)
            {
                DataView dv = new DataView(lichbanphong);
                dv.RowFilter = "maphong='" + dsngay[i].maphong + "' and thoigianbatdau<='" + dsngay[i].getngay() + "' and thoigianketthuc>='" + dsngay[i].getngay() + "'";
                if (dv.Count == 0)
                {
                    cathi = dsngay[i].timcathi(int.Parse(lop["thoiluongthi"].ToString()));
                    if (dsngay[i].kiemtrasucchua(siso) && cathi != null && !dsngay[i].kiemtrat7() && dsngay[i].checkloaiphong(int.Parse(lop["idhinhthucthi"].ToString())))
                    {
                        s[0] = "OK";
                        s[1] = cathi;
                        s[2] = dsngay[i].getngay().ToString();
                        dr0["cathi"] = cathi;
                        dr0["malop"] = lop["malopmonhoc"];
                        dr0["siso"] = siso;
                        dr0["maphong"] = dsngay[i].getmaphong();
                        dr0["ngay"] = dsngay[i].getngay();
                        dr0["succhua"] = dsngay[i].getsucchua();
                        dr0["thoiluongthi"] = lop["thoiluongthi"];
                        kq.Rows.Add(dr0);
                        dsngay[i].setcathi(int.Parse(cathi));
                        return s;
                    }
                    else
                    {
                        if ((dsngay[i].getsucchua() / 2 + 5) - siso >= 0 && (dsngay[i].getsucchua() / 2 + 5) - siso < min && !dsngay[i].kiemtrat7())
                        {
                            cathi = dsngay[i].timcathi(int.Parse(lop["thoiluongthi"].ToString()));
                            min = (dsngay[i].getsucchua() / 2 + 5) - siso;
                            maphong = dsngay[i].getmaphong();
                            ngay = dsngay[i].getngay().ToString();
                            succhua = dsngay[i].getsucchua();
                            h = i;
                        }

                    }
                }
            }
            if (maphong == "")
                return null;
            else
            {
                s[0] = "OK";
                s[1] =cathi;
                s[2] = ngay;
                dr0["cathi"] = cathi;
                dr0["malop"] = lop["malopmonhoc"];
                dr0["siso"] = siso;
                dr0["maphong"] = maphong;
                dr0["ngay"] = ngay;
                dr0["succhua"] = succhua;
                dr0["thoiluongthi"] = lop["thoiluongthi"];
                kq.Rows.Add(dr0);
                dsngay[h].setcathi(int.Parse(cathi));
                return s;
            }
        }
        
        float tinhmo(int x, int a, int b, int c, int d)
        {
            float temp1 = (x - a) / (b - a);
            float temp2 = (d - x) / (d - c);
            float temp3=(temp1<temp2?temp1:temp2);
            return temp3 < 1 ? temp3 : 1;
        }
        string[] timngayphuhop(DataRow dr,int siso)
        {
            DataRow dr0 = kq.NewRow();
            string[] ketqua = new string[3];
            string s = "";
            dsngay.Sort((x, y) => y.getsucchua().CompareTo(x.getsucchua()));
            for (int i = 0; i < dsngay.Count; i++)
            {
                s = dsngay.ElementAt(i).timcathi(int.Parse(dr["thoiluongthi"].ToString()));
                if (s != null && dsngay[i].checkloaiphong(int.Parse(dr["idhinhthucthi"].ToString()))&&!dsngay[i].kiemtrat7())
                {
                    DataView dv = new DataView(lichbanphong);
                    dv.RowFilter = "maphong='" + dsngay[i].maphong + "' and thoigianbatdau<='" + dsngay[i].getngay() + "' and thoigianketthuc>='" + dsngay[i].getngay() + "'";
                    if (dv.Count == 0)
                    {
                        if (dsngay[i].kiemtrasucchua(siso))
                        {
                            dr0["cathi"] = s;
                            dr0["malop"] = dr["malopmonhoc"];
                            dr0["siso"] = siso;
                            dr0["maphong"] = dsngay[i].getmaphong();
                            dr0["ngay"] = dsngay[i].getngay();
                            dr0["succhua"] = dsngay[i].getsucchua();
                            dr0["thoiluongthi"] = dr["thoiluongthi"];
                            kq.Rows.Add(dr0);
                            dsngay.ElementAt(i).setcathi(int.Parse(s));
                            ketqua[0] = "OK";
                            ketqua[1] = s;
                            ketqua[2] = dsngay[i].getngay().ToString();
                            return ketqua;
                        }

                    }
                }

            }
            return null;
        }
        int[] chialopthi(DataRow dr)
        {
            int[] ketqua = new int[2];
            int m = 2;
            int siso = int.Parse(dr["siso"].ToString()) / m;            
            bool flag=true;           
            while (flag)
            {
                List<clsNgay> listphong = ktsoluongphong(siso, int.Parse(dr["thoiluongthi"].ToString()));
                if (m > listphong.Count)
                {
                    m++;
                    siso = int.Parse(dr["siso"].ToString()) / m;
                }
                else
                {
                    flag = false;
                    ketqua[0] = m;
                    ketqua[1] = int.Parse(dr["siso"].ToString()) / m;
                }
                   
            }
            return ketqua;

        }
        bool ghepngay(string[] ngaythi, DataRow dr,int siso)
        {
            DataRow dr0 = kq.NewRow();
            int min = 10000;
            int h=0;
            string maphong = "", ngay = "", succhua = "";
            var result=dsngay;
            for (int i = 0; i < dsngay.Count; i++)
            {
                result = dsngay.Where(p => p.getngay().ToString() == ngaythi[2]).ToList();
                for (int j = 0; j < result.Count; j++)
                {
                    if ((result[j].getsucchua() / 2 + 5) - siso >= 0 && (result[j].getsucchua() / 2 + 5) - siso < min)
                    {
                        DataView dv = new DataView(lichbanphong);
                        dv.RowFilter = "maphong='" + result.ElementAt(j).maphong + "' and thoigianbatdau<='" + result.ElementAt(j).getngay() + "' and thoigianketthuc>='" + dsngay[i].getngay() + "'";
                        if (dv.Count == 0)
                        {
                            bool s = result.ElementAt(j).checkcathi(int.Parse(ngaythi[1]));
                            if (s && result[j].checkloaiphong(int.Parse(dr["idhinhthucthi"].ToString())) && !result.ElementAt(j).kiemtrat7())
                            {
                                int min1 = (result[j].getsucchua() / 2 + 5) - siso;
                                if (result[j].kiemtrasucchua(siso))
                                {
                                    dr0["cathi"] = ngaythi[1];
                                    dr0["malop"] = dr["malopmonhoc"];
                                    dr0["siso"] = siso;
                                    dr0["maphong"] = result.ElementAt(j).getmaphong();
                                    dr0["ngay"] = result.ElementAt(j).getngay();
                                    dr0["succhua"] = result.ElementAt(j).getsucchua();
                                    dr0["thoiluongthi"] = dr["thoiluongthi"];
                                    kq.Rows.Add(dr0);
                                    result.ElementAt(j).setcathi(int.Parse(dr0["cathi"].ToString()));
                                    return true;
                                }
                                else
                                {
                                    if ((result[j].getsucchua() / 2 + 5) - siso >= 0 && (result[j].getsucchua() / 2 + 5) - siso < min && !result.ElementAt(j).kiemtrat7())
                                    {
                                        min = (result[j].getsucchua() / 2 + 5) - siso;
                                        maphong = result.ElementAt(j).getmaphong();
                                        ngay = result.ElementAt(j).getngay().ToString();
                                        succhua = result.ElementAt(j).getsucchua().ToString();
                                        h = j;
                                    }
                                }

                            }
                        }
                    }
                }
            }
            if (maphong != "")
            {
                dr0["cathi"] = ngaythi[1];
                dr0["malop"] = dr["malopmonhoc"];
                dr0["siso"] = siso;
                dr0["maphong"] = maphong;
                dr0["ngay"] = ngay;
                dr0["succhua"] = succhua;
                dr0["thoiluongthi"] = dr["thoiluongthi"];
                kq.Rows.Add(dr0);
                result.ElementAt(h).setcathi(int.Parse(ngaythi[1]));
                return true;
            }
            return false;
          
        }
        DataTable taovephai()
        {
            DataTable rs = new DataTable();
            string sql2 = "SELECT MAPHONG,SUCCHUA,idloai as loaiphong FROM PHONGHOC order by succhua";
            SqlCommand cmd = new SqlCommand(sql2, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(rs);
            return rs;
        }
        DataTable laylichbanphong()
        {
            DataTable rs = new DataTable();
            string sql = "select * from lichbanphong";
            SqlCommand cmd = new SqlCommand(sql, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(rs);
            return rs;
        }
        DataTable taovetrai()
        {
            DataTable rs = new DataTable();
            rs.Columns.Add("malopmonhoc");
            rs.Columns.Add("mamonhoc");
            rs.Columns.Add("tenmon");
            rs.Columns.Add("macb");
            rs.Columns.Add("thoiluongthi");
            rs.Columns.Add("siso");
            rs.Columns.Add("idhinhthucthi");
            DataTable monhoc = new DataTable();
            string sql = "select * from monhoc";
            SqlCommand cmd = new SqlCommand(sql, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(monhoc);
            DataView dv = new DataView(monhoc);
            for (int i = 0; i < monhoc.Rows.Count; i++)
            {
                DataTable temp = new DataTable();
                string sql1 = "select l.malopmonhoc,tenmon,macb,idlopmonhoc,thoiluongthi,idhinhthucthi from lopmonhoc l,monhoc m where l.mamon=m.mamon and  l.mamon='" + monhoc.Rows[i]["mamon"].ToString() + "'";
                string s = monhoc.Rows[i]["mamon"].ToString();
                SqlCommand cmd1 = new SqlCommand(sql1, con);
                SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
                da1.Fill(temp);
                for (int j = 0; j < temp.Rows.Count; j++)
                {
                    DataRow dr = rs.NewRow();
                    
                    string sql2 = "select count(*) as siso from chitietlopmonhoc where idlopmonhoc='" + temp.Rows[j]["idlopmonhoc"].ToString() + "'";
                    DataTable temp1 = new DataTable();
                    SqlCommand cmd2 = new SqlCommand(sql2, con);
                    SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
                    da2.Fill(temp1);
                    if (int.Parse(temp1.Rows[0][0].ToString()) > 0)
                    {
                        dr["siso"] = temp1.Rows[0][0].ToString();
                        dr["mamonhoc"] = monhoc.Rows[i]["mamon"];
                        dr["malopmonhoc"] = temp.Rows[j]["malopmonhoc"];
                        dr["tenmon"] = temp.Rows[j]["tenmon"];
                        dr["macb"] = temp.Rows[j]["macb"];
                        dr["thoiluongthi"] = temp.Rows[j]["thoiluongthi"];
                        dr["idhinhthucthi"] = temp.Rows[j]["idhinhthucthi"];
                        rs.Rows.Add(dr);
                    }
                }
            }
            return rs;
        }
        DataTable getmonhoc()
        {
            DataTable monhoc = new DataTable();
            string sql = "select distinct(mamon) from lopmonhoc";
            SqlCommand cmd = new SqlCommand(sql, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(monhoc);
            return monhoc;
        }
        //void heap_sort(List<clsNgay> ds)
        //{
        //    int i,j,size,k;
        //    clsNgay tg,tg2;
        //    tg=new clsNgay();
        //    tg2=new clsNgay();
        //    size = ds.Count;
        //     while(size>=0)
        //     {
        //         k=(int)(size-1)/2; 
        //         while(k>=0)
        //         {
        //            i=k; 
        //            while(i*2<size)
        //            {
        //                j=2*i+1;
        //                if ((j+1<=size)&&(ds[j].nhohon(ds[j+1])))//***
        //                j=j+1;
        //                if (ds[i].nhohon(ds[j])) //***
        //                 {
        //                 tg.add(ds[i]);
        //                 ds[i].add(ds[j]);
        //                 ds[j].add(tg);
        //                 i=j;
        //     }
        //    else break;
        //    }
        //   k--;
        //   }
        //  tg2.add(ds[0]);
        //  ds[0].add(ds[size]);
        //  ds[size].add(tg2);
        //  size--;
        //  }
        //}
        List<clsNgay> ktsoluongphong(int siso,int thoigianthi)
        {
            List<clsNgay> rs = new List<clsNgay>();
            int count = 0;
            int left, right, temp;            
            left=0;
            right=dsngay.Count - 1;
            temp=(left+right)/2;
            //while (right - left > 10)
            //{
            //    if (dsngay[temp].getsucchua() == siso)
            //    {
            //        int i = temp;
            //        while (dsngay[temp].getsucchua() <= siso || dsngay[i].getsucchua() >= siso)
            //        {
            //            if (dsngay[temp].getsucchua() <= siso)
            //                temp--;
            //            if (dsngay[i].getsucchua() >= siso)
            //                i++;
            //        }
            //        left = temp;
            //        right = i;
            //        break;
            //    }
            //    if (dsngay[temp].getsucchua() < siso)
            //    {
            //        left = temp;
            //        temp = (left + right) / 2;
            //    }
            //    else
            //    {
            //        right = temp;
            //        temp = (left + right) / 2;
            //    }
            //}
            for (int i=0; i <dsngay.Count;i++ )
            {
                if (dsngay[i].timcathi(thoigianthi) != null && dsngay[i].kiemtrasucchua(siso))
                    rs.Add(dsngay[i]);
            }
            return rs;
        }

    }
    
}
